package server.model.meeting;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Logbook {

	private Message mesages;
	private FileWriter fileWriter;
	private BufferedWriter bufferedWriter;
	private PrintWriter printWriter;

	public Logbook(Meeting _meeting) {				
		// Create a file to log to
		// Filename = date of today + meetingname + starttime
		StringBuilder sBuilder = new StringBuilder();
		
		// Date of today
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		sBuilder.append(formatter.format(_meeting.getMeetingInfo().getStartDate()));		
		sBuilder.append("_");
		
		// Name of the meeting
		sBuilder.append(_meeting.getMeetingInfo().getName());
		sBuilder.append("_");

		// Starttime		 
		formatter = new SimpleDateFormat("(HH.mm)");
		sBuilder.append(formatter.format(_meeting.getMeetingInfo().getStartDate()));
		
		sBuilder.append(".txt");
			
		String fileName = sBuilder.toString();
		
		// Vars for file
		formatter.applyPattern("dd-MM-yyyy");
		String startDate = formatter.format(_meeting.getMeetingInfo().getStartDate());
		formatter.applyPattern("HH:mm");
		String startTime = formatter.format(_meeting.getMeetingInfo().getStartDate());
		
		String deelnemers = "";
		for(int i = 0; i < _meeting.getParticipants().size(); i++)
		{
			if(i == 0)
			{
				deelnemers += _meeting.getParticipants().get(i).getName();	
			}
			else
			{
				deelnemers += ", " + _meeting.getParticipants().get(i).getName();
			}
		}
		
		try {
			this.fileWriter = new FileWriter(fileName);
			this.bufferedWriter = new BufferedWriter(this.fileWriter);
			this.printWriter = new PrintWriter(this.bufferedWriter);
			this.printWriter.println("Naam: " + _meeting.getMeetingInfo().getName());
			this.printWriter.println("Datum: " + startDate);
			this.printWriter.println("Aanvang: " + startTime);
			this.printWriter.println("Deelnemers: " + deelnemers);
		} catch (IOException e) {
			e.printStackTrace();
		} 		
	}

	public void addMessage(Message message) {
		StringBuilder sBuilder = new StringBuilder();
		
		// Timestamp
		SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
		sBuilder.append(formatter.format(message.getTimestamp()));
		sBuilder.append(" - ");

		// Sender
		sBuilder.append(message.getSender());
		sBuilder.append(" zegt:");
		
		// Adding Timestamp + Sender 
		this.printWriter.println(sBuilder.toString());
		
		// Adding Message
		this.printWriter.println(message.getContent());		
	}

	public Message getMesages() {
		return mesages;
	}

}
